package services;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import domain.Person;

@Service("persionService")
@Transactional
public class PersonService {
	protected static Logger logger = Logger.getLogger(PersonService.class);
	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;

	public List<Person> getAll() {
		logger.info("Retrived all person");
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("FROM Person");
		return query.list();
	}

	public Person getPersonById(Integer id) {
		logger.info("Get person by Id");
		Session session = null;
		Transaction txn = null;
		try {
			session = sessionFactory.getCurrentSession();
			txn = session.getTransaction();
			Person person = (Person) session.get(Person.class, id);
//			txn.commit();
			return person;
		} catch (HibernateException ex) {
			if (txn != null)
				txn.rollback();
			ex.printStackTrace();
			return null;
		}
	}

	public void addPerson(Person person) {
		logger.info("Adding new person");
		Session session = null;
		Transaction txn = null;
		try {
			session = sessionFactory.getCurrentSession();
			txn = session.getTransaction();
			session.save(person);
//			txn.commit();
		} catch (HibernateException ex) {
			if (txn != null)
				txn.rollback();
			ex.printStackTrace();
		}
	}

	public void deletePerson(Integer id) {
		logger.info("Deleting a person");
		Session session = null;
		Transaction txn = null;
		try {
			session = sessionFactory.getCurrentSession();
			txn = session.getTransaction();
			Person person = getPersonById(id);
			session.delete(person);
//			txn.commit();
		} catch (HibernateException ex) {
			if (txn != null) {
				txn.rollback();
			}
			ex.printStackTrace();
		}
	}

	public void editPerson(Person person) {
		logger.info("Editting exist person");
		Session session = null;
		Transaction txn = null;
		try {
			session = sessionFactory.getCurrentSession();
			txn = session.getTransaction();
			Person existPerson = getPersonById(person.getId());
			existPerson.setFirstName(person.getFirstName());
			existPerson.setLastName(person.getLastName());
			existPerson.setAge(person.getAge());
			existPerson.setAddress(person.getAddress());
			session.save(existPerson);
//			txn.commit();
		} catch (HibernateException ex) {
			if (txn != null) {
				txn.rollback();
				ex.printStackTrace();
			}
		}
	}
}
